package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import calculation.MatrixLibrary;
import common.MyButton;
import common.MyLabel;
import common.MyTextField;

public class DialogAddByFile extends JFrame implements ActionListener {
	private FrameMain f = null;

	private MyLabel label = new MyLabel(new ImageIcon("./image/dialogAddByFile.png"));
	private MyTextField text1 = new MyTextField();
	private MyTextField text2 = new MyTextField();
	private MyTextField text3 = new MyTextField();
	private MyButton button1 = new MyButton(new ImageIcon("./image/ok.png"));
	private MyButton button2 = new MyButton(new ImageIcon("./image/browse.png"));
	private JFileChooser fc;
	
	public DialogAddByFile(FrameMain frameMain) {
		f = frameMain;
		fc = new JFileChooser();
		setSize(451, 220);
		setResizable(false);

		label.setBounds(0, 0, 451, 220);

		text1.setBounds(145, 65, 235, 25);
		text2.setBounds(145, 105, 170, 25);
		text3.setBounds(390, 68, 30, 20);
		button1.setBounds(148, 133, 154, 52);
		button2.setBounds(315, 91, 118, 56);

		label.add(button1);
		label.add(button2);
		label.add(text1);
		label.add(text2);
		label.add(text3);
		this.add(label);

		button1.addActionListener(this);
		button2.addActionListener(this);

	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == button2) {

			if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
				text2.setText(fc.getSelectedFile().getAbsolutePath());
				text2.setEditable(false);
			}
		}

		if (e.getSource() == button1) {
			if (!text1.getText().equals("")) {
				f.getFileHandler().copyFile(fc.getSelectedFile().getAbsolutePath(),
						f.getFileHandler().getLibraryDirectoryPath(), text1.getText());
				
				f.getInputHandler().loadMatricesFromLibraryDirectory();
				String[] nameList = (String[]) MatrixLibrary.getNameList().toArray(new String[0]);
				f.getPanelDisplayMatrixList().updateMyLayout(nameList);
				f.getPanelCalculationBar().setMatrixNameList(nameList);
				
				f.getDialogAddByFile().setVisible(false);
			} else {
				text3.setText("error");
				//text3.setFont(new Font("", Font.BOLD, 12));
				text3.setEditable(false);
			}
		}

	}
}
